package com.hnkywl.sts.action.jhgl;


import com.hnkywl.sts.action.flow.assign.RegectTaskSingleBackWayCmd;
import com.hnkywl.sts.entity.htgl.Cght;
import com.hnkywl.sts.entity.htgl.Ht;
import com.hnkywl.sts.entity.jhgl.*;
import com.hnkywl.sts.entity.organ.Lj;
import com.hnkywl.sts.entity.organ.Nbgs;
import com.hnkywl.sts.entity.sys.Gncz;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.service.flow.FlowService;
import com.hnkywl.sts.service.htgl.CghtService;
import com.hnkywl.sts.service.jhgl.WzjhService;
import com.hnkywl.sts.service.organ.NbgsService;
import com.hnkywl.sts.service.sys.GnczService;
import com.hnkywl.sts.service.sys.YgService;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.jbpm.api.*;
import org.jbpm.api.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: ZHUCHG
 * Date: 13-4-1
 * Time: 下午6:20
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/jhgl/wzjhgl")
public class WzjhglAction extends SimpleActionSupport {
    private Long id;
    private Long xyId;
    private String xyType;
    private Date date;
    //类型
    private String type;
    //计划年份
    private String jhnf;
    //计划月份
    private String jhyf;
    //协议号
    private String jhbh;
    //上报公司ID
    private Long sbgsId;
    //供应商ID
    private Long gysId;
    //物资编码
    private String wzbm;
    //审批状态
    private String zt;
    //统筹公司ID
    private Long tcgsId;
    //分页组件 起始位置
    private int page;
    //分页组件 页面大小
    private int rows;

    private Long ssgsId;

    private String result;

    private String taskId;

    private String content;

    private String processInstanceId;

    private String executionId;

    private Long gsId;
    private Long ygGsId;
    private String ygGs;
    private Yg yg;

    private String ygGsbm;
    private Nbgs zgs;
    private Map<String, String> rzlx;

    private Cgwzjh cgwzjh;
    private Tpwzjh tpwzjh;
    private Zgwzjh zgwzjh;
    private List<Zgwzjhmx> zgwzjhmxList;
    private List<Tpwzjhmx> tpwzjhmxList;

    private String wzjhmxList;

    private WzjhService wzjhService;

    //功能操作
    private List<Gncz> gnczList;
    private GnczService gnczService;
    private NbgsService nbgsService;


    private FlowService flowService;

    private ProcessEngine processEngine;

    private TaskService taskService;

    private ExecutionService executionService;

    private HistoryService historyService;


    @Action("wzjhgl")
    public String wzjhgl() {
        date = new Date();//initStartDate();
        gnczList = gnczService.findGnczByJsAndUrl(request.getServletPath());
        return SUCCESS;
    }

    @Action("wzjhgl_content")
    public String wzjhglContent() {
        ygGsId = YgService.getCurrentYgZgGsId();
        gsId = YgService.getCurrentYgGsId();
        ygGs = YgService.getCurrentYgGs();
        yg = YgService.getCurrentYg();
        if ("Zgwzjh".equalsIgnoreCase(type) && id != null) {
            zgwzjh = wzjhService.findZgwzjh(id);
        }
        if ("Tpwzjh".equalsIgnoreCase(type) && id != null) {
            tpwzjh = wzjhService.findTpwzjh(id);
        } else {
            ygGsbm = YgService.getCurrentYgZgGsCode();
            List<Nbgs> roots = nbgsService.findAllRootNbgs();
            if (!CollectionUtils.isEmpty(roots))
                zgs = roots.get(0);
        }
        date = new Date();
//        date = initStartDate();
        rzlx = Xy.RZLX.getRzlxList();
        return SUCCESS;
    }

    private Date initStartDate() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(cal.YEAR);
        int month = cal.get(cal.MONTH);
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month + 1);
        cal.set(Calendar.DATE, 1);
        return cal.getTime();
    }

    @Action("zgwzjhSbgs")
    public void zgwzjhSbgs() {
        ygGsId = YgService.getCurrentYgZgGsId();
        ygGs = YgService.getCurrentYgZgGs();
        ygGsbm = YgService.getCurrentYgZgGsCode();
        List<Nbgs> roots = nbgsService.findAllRootNbgs();
        if (!CollectionUtils.isEmpty(roots))
            zgs = roots.get(0);
        List<String> temp = new ArrayList<String>();
        if (zgs != null && zgs.getId().equals(ygGsId))
            temp.add("{\"id\":" + zgs.getId() + ",\"name\":\"" + zgs.getQc() + "\",\"type\":\"\"}");   //type为空申报机构获取下属公司
        else
            temp.add("{\"id\":" + zgs.getId() + ",\"name\":\"" + zgs.getQc() + "\",\"type\":\"zgs\"}");   //type为不空申报机构至获取当前主管公司
        if ((zgs != null && !zgs.getId().equals(ygGsId)) || zgs == null)
            temp.add("{\"id\":" + ygGsId + ",\"name\":\"" + ygGs + "\",\"type\":\"\"}");   //type为空申报机构获取下属公司
        String json = StringUtils.join(temp, ",");
        if (StringUtils.isNotEmpty(json))
            renderJson("[" + json + "]");
        else
            renderJson("[]");
    }

    @Action("wzjhList")
    public void wzjhList() {
        renderJson(wzjhService.findList(type, jhnf, jhyf, jhbh, sbgsId, gysId, zt, tcgsId, wzbm, page, rows));
    }

    @Action("wzjhCreateZjjhList")
    public void wzjhCreateZjjhList() {
        renderJson(wzjhService.findWzjhCreateZjjh(type, ssgsId, zt, page, rows));
    }

    @Action("wzjhCreateHtList")
    public void wzjhCreateHtList() {
        renderJson(wzjhService.findWzjhCreateHt(ssgsId, zt, page, rows));
    }

    @Action("wzjhgl_detail")
    public String wzjhglDetail() {
        cgwzjh = wzjhService.findCgwzjh(id);
        if (cgwzjh.getXy() != null) {
            xyId = cgwzjh.getXy().getId();
            xyType = cgwzjh.getXy().getClass().getSimpleName();
        }

        if (cgwzjh instanceof Zgwzjh) {
            type = "Zgwzjh";
            zgwzjh = (Zgwzjh) cgwzjh;
        } else if (cgwzjh instanceof Tpwzjh) {
            type = "Tpwzjh";
            tpwzjh = (Tpwzjh) cgwzjh;
        }

        return SUCCESS;
    }

    @Action("wzjhglsp_detail")
    public String wzjhglspDetail() {
        if ("Zgwzjh".equalsIgnoreCase(type)) {
            type = "Zgwzjh";
            zgwzjh = wzjhService.findZgwzjh(id);
            cgwzjh = (Cgwzjh) zgwzjh;
        }
        if ("Tpwzjh".equalsIgnoreCase(type)) {
            type = "Tpwzjh";
            tpwzjh = wzjhService.findTpwzjh(id);
            cgwzjh = (Cgwzjh) tpwzjh;
        }
        return SUCCESS;
    }

    @Action("wzjhmxList")
    public void wzjhmxList() {
        if ("Zgwzjh".equalsIgnoreCase(type)) {
            renderText(wzjhService.findZgwzjhmxByZgwzjh(id));
            return;
        }
        if ("Tpwzjh".equalsIgnoreCase(type)) {
            renderText(wzjhService.findTpwzjhmxByTpwzjh(id));
            return;
        }
    }

    @Action("save_wzjh")
    public void save() {
        try {
            if ("XyZgwzjh".equalsIgnoreCase(type) || "LjZgwzjh".equalsIgnoreCase(type)) {
                wzjhService.saveZgwzjh(zgwzjh, zgwzjhmxList);
                renderText("{\"statusCode\":\"200\", \"message\":\"保存自购物资计划成功!\"}");
                return;
            }
            if ("Tpwzjh".equalsIgnoreCase(type)) {
                //新增统配物资计划
                wzjhService.saveTpwzjh(tpwzjh, tpwzjhmxList);
                renderText("{\"statusCode\":\"200\", \"message\":\"保存统配物资计划成功!\"}");
                return;
            }
            renderText("{\"statusCode\":\"300\", \"message\":\"物资计划类型参数错误!\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("edit_wzjh")
    public void edit() {
        try {
            if ("Zgwzjh".equalsIgnoreCase(type)) {
                zgwzjh.setLastUpdated(new Date());
                wzjhService.editZgwzjh(zgwzjh, zgwzjhmxList);
                renderText("{\"statusCode\":\"200\", \"message\":\"修改自购物资计划成功!\"}");
                return;
            }
            if ("Tpwzjh".equalsIgnoreCase(type)) {
                //修改统配物资计划
                tpwzjh.setLastUpdated(new Date());
                wzjhService.editTpwzjh(tpwzjh, tpwzjhmxList);
                renderText("{\"statusCode\":\"200\", \"message\":\"修改统配物资计划成功\"}");
                return;
            }
            renderText("{\"statusCode\":\"300\", \"message\":\"物资计划类型参数错误!\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("delete")
    public void delete() {
        try {
            if ("Zgwzjh".equalsIgnoreCase(type)) {
                wzjhService.deleteZgwzjh(id);
                renderText("{\"statusCode\":\"200\", \"message\":\"删除自购物资计划成功!\"}");
                return;
            }
            if ("Tpwzjh".equalsIgnoreCase(type)) {
                wzjhService.deleteTpwzjh(id);
                renderText("{\"statusCode\":\"200\", \"message\":\"删除统配物资计划成功\"}");
                return;
            }
            renderText("{\"statusCode\":\"300\", \"message\":\"物资计划类型参数错误!\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }


    @Action("commit_wzjh")
    public void commitWzjh() {
        try {
            cgwzjh = wzjhService.findCgwzjh(id);
            String processName = ("zgwzjh".equalsIgnoreCase(type) ? "自购物资计划流程" : "统配物资计划流程");
            if (this.flowService.checkFlowStart(processName)) {
                String contain = StringUtils.EMPTY;
                if ("zgwzjh".equalsIgnoreCase(type)) {
                    if (cgwzjh.getXy() != null || cgwzjh.getCreateDepartment().getId() == 30
                            || cgwzjh.getCreateDepartment().getId() == 26
                            || cgwzjh.getCreateDepartment().getId() == 27
                            || cgwzjh.getCreateDepartment().getId() == 28
                            || cgwzjh.getCreateDepartment().getId() == 29|| cgwzjh.getCreateDepartment().getId() == 8131
                            || cgwzjh.getCreateDepartment().getId() == 8132
                            || cgwzjh.getCreateDepartment().getId() == 8133
                            || cgwzjh.getCreateDepartment().getId() == 8134) {
                        contain = "协议";
                    }
                } else if ("Tpwzjh".equalsIgnoreCase(type)) //添加参数用于判断用户
                    contain = ((Tpwzjh) cgwzjh).getTcbm().getId().toString();
                String processInstanceId = this.flowService.regTask(cgwzjh.getProcessInstanceId(), processName, contain);
                cgwzjh.setProcessInstanceId(processInstanceId);
                cgwzjh.setZt("ytj");
            } else
                cgwzjh.setZt("ysp");
            wzjhService.saveCgwzjh(cgwzjh);
            renderJson("{\"statusCode\":\"200\", \"message\":\"提交物资计划成功!\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderJson("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("wzjhByProcessInstance")
    public void wzjhByProcessInstance() {
        Cgwzjh cgwzjh;
        String processInstanceId = StringUtils.EMPTY;
        Execution execution = this.executionService.findExecutionById(executionId);
        if (execution != null) {
            cgwzjh = this.wzjhService.findWzjhDetailByProcessInstance(execution.getProcessInstance().getId());
            processInstanceId = execution.getProcessInstance().getId();
        } else {
            cgwzjh = this.wzjhService.findWzjhDetailByProcessInstance(executionId);
            processInstanceId = executionId;
        }
        String xyJson = "{'id':'" + cgwzjh.getId() + "','type':'" + cgwzjh.getClass().getSimpleName() + "','businessNo':'" + cgwzjh.getJhbh() + "','processInstanceId':'" + processInstanceId + "'}";
        this.renderText(xyJson);
    }

    @Action(value = "examineTask")
    public void examineTask() {
        if (this.result.equals("审核")) {
            Map<String, Object> var = new HashMap<String, Object>();
            var.put("owner", YgService.getCurrentYg().getId());
            var.put("opera", YgService.getCurrentYgGs() + "--" + YgService.getCurrentYgName());
            var.put("result", "审核通过");
            var.put("content", content);
            var.put("time", new Date());
            Task currentTask = this.taskService.getTask(taskId);
            String executionId = currentTask.getExecutionId();
            executionService.createVariables(executionId, var, true);


            Execution execution = this.executionService.findExecutionById(executionId);
            Cgwzjh cgwzjh = wzjhService.findWzjhDetailByProcessInstance(execution.getProcessInstance().getId());
            var.put("status", result);

            if (cgwzjh.getClass().getSimpleName().equalsIgnoreCase("Zgwzjh")) {
                if (cgwzjh.getXy() != null || cgwzjh.getCreateDepartment().getId() == 30
                        || cgwzjh.getCreateDepartment().getId() == 26
                        || cgwzjh.getCreateDepartment().getId() == 27
                        || cgwzjh.getCreateDepartment().getId() == 28
                        || cgwzjh.getCreateDepartment().getId() == 29
                        || cgwzjh.getCreateDepartment().getId() == 8131
                        || cgwzjh.getCreateDepartment().getId() == 8132
                        || cgwzjh.getCreateDepartment().getId() == 8133
                        || cgwzjh.getCreateDepartment().getId() == 8134) {
                    var.put("contain", "协议");
                } else {
                    var.put("contain", StringUtils.EMPTY);
                }
            } else if (cgwzjh.getClass().getSimpleName().equalsIgnoreCase("Tpwzjh")) { //添加参数用于判断用户
                this.wzjhService.updateTpwzjhmxhdsl(wzjhmxList);
                var.put("contain", ((Tpwzjh) cgwzjh).getTcbm().getId().toString());
            } else {
                var.put("contain", StringUtils.EMPTY);
            }
            this.taskService.completeTask(taskId, var);


            if (cgwzjh.getZt().equals("ybc")) {
                cgwzjh.setZt("ytj");
                wzjhService.saveCgwzjh(cgwzjh);
            }
        } else {
            String result = processEngine.execute(new RegectTaskSingleBackWayCmd(taskId, content));
            if (result.equals("change")) {
                //修改状态  ytj--->ybc
                String executionId = this.historyService.createHistoryTaskQuery().taskId(taskId).uniqueResult().getExecutionId();
                Execution execution = this.executionService.findExecutionById(executionId);
                Cgwzjh cgwzjh = wzjhService.findWzjhDetailByProcessInstance(execution.getProcessInstance().getId());
                cgwzjh.setZt("ybc");
                wzjhService.saveCgwzjh(cgwzjh);
            }
        }
        this.renderText("{\"statusCode\":\"200\", \"message\":\"审核流程成功\"}");
    }


    //============getter setter===================
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Cgwzjh getCgwzjh() {
        return cgwzjh;
    }

    public void setCgwzjh(Cgwzjh cgwzjh) {
        this.cgwzjh = cgwzjh;
    }

    public Tpwzjh getTpwzjh() {
        return tpwzjh;
    }

    public void setTpwzjh(Tpwzjh tpwzjh) {
        this.tpwzjh = tpwzjh;
    }

    public Zgwzjh getZgwzjh() {
        return zgwzjh;
    }

    public void setZgwzjh(Zgwzjh zgwzjh) {
        this.zgwzjh = zgwzjh;
    }

    public List<Zgwzjhmx> getZgwzjhmxList() {
        return zgwzjhmxList;
    }

    public void setZgwzjhmxList(List<Zgwzjhmx> zgwzjhmxList) {
        this.zgwzjhmxList = zgwzjhmxList;
    }

    public List<Tpwzjhmx> getTpwzjhmxList() {
        return tpwzjhmxList;
    }

    public void setTpwzjhmxList(List<Tpwzjhmx> tpwzjhmxList) {
        this.tpwzjhmxList = tpwzjhmxList;
    }

    public List<Gncz> getGnczList() {
        return gnczList;
    }

    public void setGnczList(List<Gncz> gnczList) {
        this.gnczList = gnczList;
    }

    //================getter===================
    public Date getDate() {
        return date;
    }

    public Long getYgGsId() {
        return ygGsId;
    }

    public String getYgGs() {
        return ygGs;
    }

    public Yg getYg() {
        return yg;
    }

    public void setYg(Yg yg) {
        this.yg = yg;
    }

    public Map<String, String> getRzlx() {
        return rzlx;
    }

    public Nbgs getZgs() {
        return zgs;
    }

    //================setter===================
    public void setYgGsbm(String ygGsbm) {
        this.ygGsbm = ygGsbm;
    }

    public void setJhnf(String jhnf) {
        this.jhnf = jhnf;
    }

    public void setJhyf(String jhyf) {
        this.jhyf = jhyf;
    }

    public String getJhbh() {
        return jhbh;
    }

    public void setJhbh(String jhbh) {
        this.jhbh = jhbh;
    }

    public void setSbgsId(Long sbgsId) {
        this.sbgsId = sbgsId;
    }

    public void setGysId(Long gysId) {
        this.gysId = gysId;
    }

    public void setZt(String zt) {
        this.zt = zt;
    }

    public void setTcgsId(Long tcgsId) {
        this.tcgsId = tcgsId;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public void setSsgsId(Long ssgsId) {
        this.ssgsId = ssgsId;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getProcessInstanceId() {
        return processInstanceId;
    }

    public void setProcessInstanceId(String processInstanceId) {
        this.processInstanceId = processInstanceId;
    }

    public String getExecutionId() {
        return executionId;
    }

    public void setExecutionId(String executionId) {
        this.executionId = executionId;
    }

    public String getWzjhmxList() {
        return wzjhmxList;
    }

    public void setWzjhmxList(String wzjhmxList) {
        this.wzjhmxList = wzjhmxList;
    }

    public String getWzbm() {
        return wzbm;
    }

    public void setWzbm(String wzbm) {
        this.wzbm = wzbm;
    }

    public Long getGsId() {
        return gsId;
    }

    public void setGsId(Long gsId) {
        this.gsId = gsId;
    }

    public Long getXyId() {
        return xyId;
    }

    public void setXyId(Long xyId) {
        this.xyId = xyId;
    }

    public String getXyType() {
        return xyType;
    }

    public void setXyType(String xyType) {
        this.xyType = xyType;
    }

    @Autowired
    public void setWzjhService(WzjhService wzjhService) {
        this.wzjhService = wzjhService;
    }

    @Autowired
    public void setGnczService(GnczService gnczService) {
        this.gnczService = gnczService;
    }

    @Autowired
    public void setNbgsService(NbgsService nbgsService) {
        this.nbgsService = nbgsService;
    }

    @Autowired
    public void setFlowService(FlowService flowService) {
        this.flowService = flowService;
    }

    @Autowired
    public void setExecutionService(@Qualifier("executionService") ExecutionService executionService) {
        this.executionService = executionService;
    }

    @Autowired
    public void setTaskService(@Qualifier("taskService") TaskService taskService) {
        this.taskService = taskService;
    }

    @Autowired
    public void setProcessEngine(@Qualifier("processEngine") ProcessEngine processEngine) {
        this.processEngine = processEngine;
    }

    @Autowired
    public void setHistoryService(@Qualifier("historyService") HistoryService historyService) {
        this.historyService = historyService;
    }
}
